package com.example.lottery_system.service.activitystatus.impl;

import com.example.lottery_system.common.errorcode.ServiceConstants;
import com.example.lottery_system.common.exception.ServiceException;
import com.example.lottery_system.service.ActivityService;
import com.example.lottery_system.service.activitystatus.ActivityStatusManager;
import com.example.lottery_system.service.activitystatus.operator.AbstractActivityOperator;
import com.example.lottery_system.service.dto.ConvertActivityStatusDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;


@Component
public class activityStatusManagerImpl implements ActivityStatusManager {

    private static final Logger logger = LoggerFactory.getLogger(activityStatusManagerImpl.class);

    @Autowired
    private final Map<String, AbstractActivityOperator> operatorMap = new HashMap<>();
    @Autowired
    private ActivityService activityService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void handlerEvent(ConvertActivityStatusDTO convertActivityStatusDTO) {
        // 1、活动状态扭转，有依赖性
        // 2、状态扭转可能会扩展，维护性差

        if(CollectionUtils.isEmpty(operatorMap)) {
            logger.warn("operatorMap 为空！");
            return;
        }

        Map<String, AbstractActivityOperator> currentMap = new HashMap<>(operatorMap);
        Boolean update = false;

        // 1、先处理：人员、奖品
        update = processConvertStatus(convertActivityStatusDTO, currentMap, 1);

        // 2、后处理：活动
        update = processConvertStatus(convertActivityStatusDTO, currentMap, 2) || update;


        // 3、更新缓存
        if(update) {
            activityService.cacheActivity(convertActivityStatusDTO.getActivityId());
        }

    }

    @Override
    public void rollbackHandlerEvent(ConvertActivityStatusDTO convertActivityStatusDTO) {
        // operatorMap：活动、奖品、人员
        // 活动绝对需要回滚
        for(AbstractActivityOperator operator : operatorMap.values()) {
            operator.convert(convertActivityStatusDTO);
        }

        // 缓存更新
        activityService.cacheActivity(convertActivityStatusDTO.getActivityId());
    }

    /**
     * 扭转状态
     * @param convertActivityStatusDTO
     * @param currentMap
     * @param sequence
     * @return
     */
    private Boolean processConvertStatus(ConvertActivityStatusDTO convertActivityStatusDTO,
                                         Map<String, AbstractActivityOperator> currentMap,

                                         int sequence) {
        Boolean update = false;
        // 遍历currentMap
        Iterator<Map.Entry<String, AbstractActivityOperator>> iterator = currentMap.entrySet().iterator();
        while (iterator.hasNext()) {
            AbstractActivityOperator operator = iterator.next().getValue();

            // Operator是否需要转换
            if(operator.sequence() != sequence
                || !operator.needConvert(convertActivityStatusDTO)) {
                continue;
            }

            // 需要转换：转换
            if(!operator.convert(convertActivityStatusDTO)) {
                logger.error("{}状态转换失败", operator.getClass().getName());
                throw new ServiceException(ServiceConstants.ACTIVITY_STATUS_CONVERT_ERROR);
            }
            // currentMap 删除当前Operator
            iterator.remove();
            update = true;
        }

        // 返回
        return update;
    }
}
